//
//  CycleCameraAndLibraryVC.m
//  CDSBZX
//
//  Created by dihuijun on 17/4/27.
//  Copyright © 2017年 Cycle. All rights reserved.
//

#import "CycleCameraAndLibraryVC.h"

@interface CycleCameraAndLibraryVC ()<UIImagePickerControllerDelegate>

@end

@implementation CycleCameraAndLibraryVC
/**
 *  1.初始化CycleCameraAndLibraryVC
 *
 *  @param style 打开照相机活着图库
 *
 *  @return 初始化CycleCameraAndLibraryVC
 */
- (instancetype)initWithImagePickerStyle:(imagePickerStyle)style{
    self = [super init];
    
    if (self) {
        if (style == ImagePickerStyleCamera) {
            self.sourceType = UIImagePickerControllerSourceTypeCamera;
        }else if (style == ImagePickerStylePhotoLibrary){
            self.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        }
    }
    
    return self;
}


#pragma mark --- viewDidLoad
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.allowsEditing = YES;
    self.delegate = self;
    self.view.backgroundColor = [UIColor colorWithWhite:0.875 alpha:1.00];
    
    
}
#pragma mark ---- <UIImagePickerControllerDelegate>
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    //获取编辑之后的图片
    UIImage *editImage = info[UIImagePickerControllerEditedImage];
    //将图片通过代理传出去
    [self.CycleDelegate imageChooseFinishedWithImage:editImage];
    //界面返回
    [picker dismissViewControllerAnimated:YES completion:nil];
}

/**
 *  2.保存图片到沙盒
 *
 *  @param image     要保存的图片
 *  @param imageName 保存的图片名称
 *  @param block     保存成功的值
 */
+ (void)saveImageToSandbox:(UIImage *)image andImageName:(NSString *)imageName andResultBlock:(resultBlock)block{
    //高保真压缩图片,此方法可将图片压缩,但是图片质量基本不变,第二个参数为质量参数
    NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
    //将图片写入文件
    NSString *filePath = [self filePath:imageName];
    //是否保存成功
    BOOL result = [imageData writeToFile:filePath atomically:YES];
    //保存成功传值到block中
    if (result) {
        block(result);
    }
}



/**
 *  3.沙盒中获取到的照片
 *
 *  @param imageName 读取的照片名称
 *
 *  @return 从沙盒读取到的照片
 */
+ (UIImage *)loadImageFromSandbox:(NSString *)imageName{
    //获取沙盒路径
    NSString *filePath = [self filePath:imageName];
    //根据路径读取image
    UIImage *image = [UIImage imageWithContentsOfFile:filePath];
    return  image;
}


/**
 *  4.根据文件获取沙盒路径
 *
 *  @param fileName 文件名称
 *
 *  @return 文件在沙盒中的路径
 */
+ (NSString *)filePath:(NSString *)fileName{
    //获取沙盒目录
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    //保存文件名称
    NSString *filePath = [paths[0] stringByAppendingPathComponent:fileName];
    
    return filePath;
    
    
}



@end
